<!-- components/AssignmentPeerReview.vue -->
<template>
  <div class="peer-review-container">
    <!-- 主界面表格 -->
    <el-card class="peer-review-card">
      <template #header>
        <div class="card-header">
          <h3>作业互评</h3>
        </div>
      </template>

      <el-table
        :data="assignments"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
        stripe>
        <el-table-column prop="title" label="作业标题" min-width="200">
          <template #default="{ row }">
            <div class="assignment-title">
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="due_date" label="截止日期" width="180">
          <template #default="{ row }">
            <div class="due-date">
              <i class="el-icon-time"></i>
              {{ formatDate(row.due_date) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                type="primary"
                size="small"
                @click="getPeerReviews(row.id)">
                获取互评作业
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewAssignmentDetail(row.id)">
                作业详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 互评任务列表弹窗 -->
    <el-dialog
      v-model="peerReviewDialogVisible"
      title="互评任务列表"
      width="60%"
      class="peer-review-dialog">
      <template v-if="!showReviewForm">
        <el-table
          :data="peerReviewTasks"
          style="width: 100%"
          border
          stripe>
          <el-table-column label="序号">
            <template #default="{ $index }">
              {{ $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="reviewed_at" label="评审时间" width="180">
            <template #default="{ row }">
              {{ row.reviewed_at ? formatDate(row.reviewed_at) : '未评审' }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.reviewed_at ? 'success' : 'warning'">
                {{ row.reviewed_at ? '已评审' : '待评审' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                @click="startReview(row)"
                :disabled="!!row.reviewed_at">
                {{ row.reviewed_at ? '查看评审' : '开始评审' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 评审表单界面 -->
      <template v-else>
      <div class="review-form-container">
        <el-button class="back-button" @click="showReviewForm = false">
          <el-icon><arrow-left /></el-icon> 返回列表
        </el-button>

        <div class="submission-content">
          <h4>作业内容：</h4>
          <div v-if="submissionDetail.loading" class="loading-placeholder">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="submissionDetail.error" class="error-message">
            {{ submissionDetail.error }}
          </div>
          <div v-else class="content-text">
            {{ submissionDetail.submission_content }}
          </div>

            <!-- 附件列表 -->
              <div v-if="submissionDetail.attachments && submissionDetail.attachments.length > 0" class="attachments">
            <h4>附件：</h4>
            <el-table :data="submissionDetail.attachments" style="width: 100%">
              <el-table-column prop="id" label="附件ID" width="80" />
              <el-table-column label="下载链接" min-width="300">
                <template #default="{ row }">
                  <el-button
                    type="primary"
                    link
                    @click="downloadAttachment(row.file_path)"
                  >
                    <el-icon class="el-icon--left"><Download /></el-icon>
                    下载附件
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="uploaded_at" label="上传时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.uploaded_at) }}
                </template>
              </el-table-column>
            </el-table>
          </div>

            <!-- 评分表单 -->
            <el-form
    ref="reviewFormRef"
    :model="reviewForm"
    :rules="reviewRules"
    label-width="100px"
    class="review-form">
    <el-form-item label="评分" prop="score">
      <el-input-number
        v-model="reviewForm.score"
        :min="0"
        :max="100"
        :step="1"
        :precision="1"
        controls-position="right"
        style="width: 160px"
        placeholder="请输入分数">
      </el-input-number>
      <span class="score-hint">满分 100 分</span>
    </el-form-item>
    <el-form-item label="评审反馈" prop="feedback">
      <el-input
        type="textarea"
        v-model="reviewForm.feedback"
        rows="6"
        placeholder="请输入评审反馈">
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitReview">
        提交评审
      </el-button>
    </el-form-item>
  </el-form>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 作业详情弹窗 -->
    <AssignmentDetailDialog
      v-model:visible="detailDialogVisible"
      :assignment="assignmentDetail"
      @close="handleDetailClose"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {ArrowLeft, Document} from '@element-plus/icons-vue'
import axios from 'axios'
import AssignmentDetailDialog from '@/components/assignment/AssignmentDetailDialog.vue'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})
// 状态管理
const submissionDetail = reactive({
  submission_content: '',
  attachments: [],
  loading: false,
  error: null
})
// 状态管理
const assignments = ref([])
const peerReviewTasks = ref([])
const assignmentDetail = ref(null)
const currentPeerReviewId = ref(null)
const peerReviewDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const showReviewForm = ref(false)
const reviewFormRef = ref(null)
const currentAssignmentId = ref(null)

const reviewForm = reactive({
  score: null,
  feedback: ''
})

const reviewRules = {
  score: [
    { required: true, message: '请给出评分', trigger: 'change' }
  ],
  feedback: [
    { required: true, message: '请输入评审反馈', trigger: 'blur' }
  ]
}

// 获取作业列表
const fetchAssignments = async () => {
  try {
    const response = await axios.get(`/backend/api/assignment/course/${props.courseId}/list/`, {
      withCredentials: true
    })
    assignments.value = response.data
  } catch (error) {
    console.error('获取作业列表失败:', error)
    ElMessage.error('获取作业列表失败，请稍后重试')
  }
}
//获取互评任务列表
const getPeerReviews = async (assignmentId) => {
  currentAssignmentId.value = assignmentId
  try {
    const response = await axios.get(`/backend/api/assignment/${assignmentId}/peer_review/list/`, {
      withCredentials: true
    })
    peerReviewTasks.value = response.data
    peerReviewDialogVisible.value = true
    showReviewForm.value = false
  } catch (error) {
    console.error('获取互评任务列表失败:', error)
    ElMessage.error('获取互评任务列表失败，请稍后重试')
  }
}

// 开始评审函数
const startReview = async ( peerReviewTasks) => {
  currentPeerReviewId.value =  peerReviewTasks.id
  showReviewForm.value = true
  // 重置表单
  reviewForm.score = null
  reviewForm.feedback = ''
  // 获取作业详情
  await fetchPeerReviewDetail()
}

const submitReview = async () => {
  if (!reviewFormRef.value) return

  await reviewFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      await axios.post(
        `/backend/api/assignment/peer_review/${currentPeerReviewId.value}/submit/`,
        {
          score: reviewForm.score,
          feedback: reviewForm.feedback
        },
        { withCredentials: true }
      )

      ElMessage.success('评审提交成功')
      showReviewForm.value = false
      // 重新获取任务列表以更新状态
      await getPeerReviews(currentAssignmentId.value)
    } catch (error) {
      console.error('提交评审失败:', error)
      ElMessage.error('提交评审失败，请稍后重试')
    }
  })
}
// 获取互评任务详情的函数
const fetchPeerReviewDetail = async () => {
  submissionDetail.loading = true
  submissionDetail.error = null

  try {
    const response = await axios.get(
      `/backend/api/assignment/peer_review/task/${currentPeerReviewId.value}/detail/`,
      { withCredentials: true }
    )

    // Update the mapping to match the API response structure
    submissionDetail.submission_content = response.data.submission_content
    submissionDetail.attachments = response.data.attachments || []
  } catch (error) {
    console.error('获取作业详情失败:', error)
    submissionDetail.error = '获取作业详情失败，请稍后重试'
    ElMessage.error('获取作业详情失败，请稍后重试')
  } finally {
    submissionDetail.loading = false
  }
}
const downloadAttachment = (url) => {
  try {
    // Create a temporary anchor element
    const link = document.createElement('a')
    link.href = url
    link.target = '_blank'
    link.rel = 'noopener noreferrer'

    // Trigger download
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败，请稍后重试')
  }
}
const fetchAssignmentDetail = async (assignmentId) => {
  try {
    const response = await axios.get(`/backend/api/assignment/${assignmentId}/detail/`, {
      withCredentials: true
    })
    assignmentDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败，请稍后重试')
  }
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 事件处理函数
const viewAssignmentDetail = (assignmentId) => {
  fetchAssignmentDetail(assignmentId)
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
}

// 生命周期钩子
onMounted(() => {
  fetchAssignments()
})
</script>

<style scoped>
.peer-review-container {
  padding: 20px;
}

.peer-review-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
}

.back-button {
  margin-bottom: 20px;
}

.review-form-container {
  padding: 20px;
}

.submission-content {
  margin-bottom: 30px;
}

.submission-content h4 {
  margin: 20px 0 10px;
  color: #303133;
}

.content-text {
  background-color: #f8f9fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  margin: 10px 0;
  white-space: pre-wrap;
  line-height: 1.6;
  min-height: 100px;
}

.attachments-section {
  margin: 20px 0;
}

.attachment-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f9fa;
}

.attachment-item {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.attachment-item:last-child {
  border-bottom: none;
}

.review-form {
  margin-top: 30px;
  border-top: 1px solid #dcdfe6;
  padding-top: 20px;
}

:deep(.el-table) th {
  background-color: #f5f7fa !important;
}

:deep(.el-table) td {
  padding: 8px 0;
}

:deep(.el-tag) {
  text-align: center;
  min-width: 65px;
}
.loading-placeholder {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.error-message {
  color: #f56c6c;
  padding: 20px;
  text-align: center;
  background: #fef0f0;
  border-radius: 4px;
  margin: 10px 0;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-item .el-link {
  display: flex;
  align-items: center;
  gap: 8px;
}
.submission-content {
  margin: 20px 0;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}


.attachments {
  margin-top: 20px;
}

h4 {
  margin: 10px 0;
  color: #303133;
  font-weight: 500;
}
</style>